import uvicorn
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile,Request,Form
from fastapi.staticfiles import StaticFiles
from detect import parse_opt,run as model_run ,model 
import uuid
import sqlite3

# cross origin resource sharing
import os
from fastapi.middleware.cors import CORSMiddleware
origins = ["*"]

static = StaticFiles(directory="upload")

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
base_url = "http://113.31.110.212:7777/static/"
app.mount("/static", static, name="upload")


@app.post('/upload')
async def upload_pic(req:Request):
    url = 'http://172.29.144.1:8000/static/'
    form = await req.form()
    file = form['image']
    contents = await file.read()
    with open('./upload/'+file.filename, "wb") as f:
        f.write(contents)
    return {'url': url+file.filename}

@app.post("/start_predict")
async def upload_img(req:Request):
    form = await req.form()
    file = form['file']
    iou = form['iou']
    trust = form['trust']
    print(file)
    name = uuid.uuid4().hex
    file_path = f'./upload/{file.filename}'
    with open(file_path, 'wb') as f:
        f.write(await file.read())
    
    opt = parse_opt()
    try:
        iou = float(iou)
        opt.iou_thres = iou
    except Exception as e :
        print(e)
        pass
    try:
        trust = float(trust)
        opt.conf_thres = trust
    except Exception as e :
        print(e)
        pass
    opt.source = file_path
    temp_folder = uuid.uuid4().hex
    if not os.path.exists('./upload/'+temp_folder):
        os.makedirs('./upload/'+temp_folder)
    opt.project = f'./upload/{temp_folder}'
    result = model_run(model=model,**vars(opt))
    result['url'] = base_url + temp_folder+"/exp/"+file.filename

    return {"code":200,"msg":"success","data":result }



@app.post('/upload_data_to_cloud')
async def upload_data_to_cloud(req:Request):
    payload = await req.json()
    url = payload['url']
    num = payload['num']
    name = payload['name']
    with open('./store.txt', 'a') as f:
        f.write(f"{url},{num},{name}\n")

    return {"code":200,'msg':'success'}

@app.get('/get_data_from_cloud')
async def get_data_from_cloud():
    with open('./store.txt', 'r') as f:
        data = f.readlines()
    data = [item.replace('\n','').split(',') for item in data if item != '']
    data = [{'url':item[0],'num':item[1],'name':item[2]} for item in data]
    return {"code":200,"msg":"success",'data':data}



@app.get("/test")
def hello():
    return "hello"

@app.post("/post_test")
def post_test():
    return "post_test"

# @app.get("/test_model")
# def test_model():
#     opt = parse_opt()
#     opt.source = 'test_1.jpg'
#     model_run(model=model,**vars(opt))

if __name__ == '__main__':
    uvicorn.run("api:app", host='0.0.0.0',port=7777,reload=True,workers=2)